package com.geohey.wx;

import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.geohey.AppContext;
import com.geohey.utils.JerseyUtils;
import com.geohey.utils.JsonUtils;

public class WeiXinClient {

	public static WXUserInfo getWXUserInfo(String code) {
		String url = AppContext.getInstance().getConfig("wx.token.url");
		url = String.format(url, code);
		Map values = request(url);
		String token = values.get("access_token").toString();
		String openId = values.get("openid").toString();
		url = AppContext.getInstance().getConfig("wx.userinfo.url");
		url = String.format(url, token, openId);
		values = request(url);
		String nickName = values.get("nickname").toString();
		String thumbnail = values.get("headimgurl").toString();
		return new WXUserInfo(openId, nickName, thumbnail);
	}

	private static Map request(String url) {
		Client client = ClientBuilder.newClient();
		WebTarget wt = client.target(url);
		Response resp = wt.request(MediaType.APPLICATION_JSON_TYPE).get();
		String json = JerseyUtils.readStringAndClose(resp, client);
		return JsonUtils.readMap(json);
	}
}
